package com.yunxi.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 响应时间全局过滤器
 *
 * @author: lidy
 * @date: 2025-01-20 21:26
 */
@Slf4j
@Component
public class RtGlobalFilter implements GlobalFilter, Ordered {

    /**
     * 在这里写过滤逻辑
     *
     * @param exchange exchange
     * @param chain    调用链
     * @return mono
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String uri = request.getURI().toString();
        long begin = System.currentTimeMillis();
        log.info("请求【{}】开始时间：{}", uri, begin);

        // ================= 以上是前置逻辑 =============

        // 放行
        Mono<Void> mono = chain.filter(exchange)
                .doFinally((result) -> {
                    // ================= 以下是后置逻辑 =============
                    long end = System.currentTimeMillis();
                    log.info("请求【{}】结束时间：{}，耗时：{}ms", uri, end, end - begin);
                });

        // 返回
        return mono;
    }

    /**
     * 优先级，数值越小，优先级越高
     *
     * @return 优先级数值
     */
    @Override
    public int getOrder() {
        return -1;
    }

}
